package com.tz.actions.book;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tz.entity.Book;
import com.tz.entity.Cart;
import com.tz.entity.OrderItem;
import com.tz.service.IBookService;
import com.tz.util.MyAcUtil;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by heziqian on 2016/10/21.
 */
@Namespace("/")
public class BookAction extends ActionSupport{

    Book book;

    private IBookService bookService =
            MyAcUtil.getInstance().getBean(IBookService.class);


    @Action(value = "details",
            results = {@Result(location="/details.jsp"),
                    @Result(name = "input",location = "/cart.jsp")
            })
    public String execute() {

        long bookid=book.getBookId();
        book=bookService.findBookById(bookid);

        return SUCCESS;

    }


    @Action(value = "addcart",
            results = {@Result(location="details",type = "chain"),
                    @Result(name = "input",location = "/cart.jsp")
            })
    public String execute23() throws IOException {
        long bookId=book.getBookId();
        book=bookService.findBookById(bookId);

        ActionContext context=ActionContext.getContext();
        Map<String,Object> session=context.getSession();
        Cart cart=(Cart)session.get("cart");

        OrderItem o = new OrderItem();
        o.setBook(book);
        o.setCount(1);
        o.setTotalPrice(book.getPrice());
        cart.addCart(o);

        String count=Integer.toString(cart.getCount());
        String totalprice=Double.toString(cart.getTotalPrice());

        session.put("cart",cart);

        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = response.getWriter();
        out.print("1:"+count+":"+totalprice);
        out.flush();
        out.close();

        return SUCCESS;

    }





    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }






}
